import cv2
import pytesseract
import pandas as pd
 
# 设置Tesseract的路径
pytesseract.pytesseract.tesseract_cmd = r'/data/fengyy/dateset/temp/1.农村土地承包经营权登记簿/模板一/模板一/origin_模板一_001.jpg'  # 根据实际路径修改
 
# 读取图片
image = cv2.imread('table.png')
 
# 灰度化和二值化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
 
# 寻找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
data = []
for contour in contours:
    # 近似轮廓
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
 
    # 如果近似轮廓有4个点，可能是表格的一行
    if len(approx) == 4:
        # 切割出这一行
        x, y, w, h = cv2.boundingRect(approx)
        roi = binary[y:y+h, x:x+w]
 
        # 使用Tesseract进行OCR
        text = pytesseract.image_to_string(roi, config='--psm 6')
        data.append([val.strip() for val in text.split('\n') if val.strip()])
 
# 创建Excel文件
df = pd.DataFrame(data)
df.to_excel('table.xlsx', index=False, header=False)